from django.shortcuts import render
from words_dict import service

from django.http import HttpResponse


def init_create_page(request):
    service.init_unit_list()
    unit_tuples = service.generate_unit_tuple()
    filtered_unit_list = []
    for unit in service.unit_list:
        if service.unit_word_len_dict[unit] == 0:
            continue
        filtered_unit_list.append(unit)
    data = {"total_unit": len(filtered_unit_list), "total_count": service.words_length, "unit_list": unit_tuples}
    return render(request, "index.html", data)


def init_dict(request):
    range_type = request.GET['type']
    dict_order_type = request.GET['order']
    ranges = request.GET['ranges']
    ranges_list = []
    if range_type == '2':
        ranges_list = ranges.split(',')
    service.init_dict(range_type, ranges_list, dict_order_type)
    return HttpResponse("success")


def dictate(request):
    response = service.fetch_word(request.GET['index'], request.GET['op_type'])
    return render(request, 'dictate.html', response)


def list_all_unit(request):
    service.init_unit_list()
    star_unit_tuple = ["收藏单词", len(service.star_words_tuples)]
    unit_tuples = service.generate_unit_tuple()
    response = {"unit_list": unit_tuples, "star_unit_tuple": star_unit_tuple}
    return render(request, 'unit_list.html', response)


def unit_words(request):
    unit_name, words = service.fetch_unit_words(request.GET['index'])
    response = {"unit_name": unit_name, "words": words}
    return render(request, 'words_list.html', response)


def add_word_page(request):
    return render(request, 'add_word.html')


def add_words(request):
    unit_num = request.GET['unit_num']
    unit_name = "unit_" + unit_num
    words = request.GET['words']
    words_list = words.split(',')
    service.add_words(unit_name, words_list)
    return HttpResponse("success")


def delete_word(request):
    unit_name = request.GET['unit_name']
    index = request.GET['index']
    service.cascade_delete(unit_name, index)
    return HttpResponse("success")


def star_word(request):
    unit_name = request.GET['unit_name']
    word = request.GET['word']
    service.add_star_word(word, unit_name)
    return HttpResponse("success")


def cancel_star_word(request):
    word = request.GET['word']
    service.cancel_star_word(word)
    return HttpResponse("success")


def star_word_page(request):
    response = {'words': service.star_words_tuples}
    return render(request, 'star_words_list.html', response)

